<template>
  <Modal
    :title="type === 1 ? '新建套餐' : type === 2 ? '编辑套餐' : ''"
    :visible="visible"
    size="large"
    :destroyOnClose="true"
    @cancel="handleCancel"
  >
    <template #footer>
      <Space>
        <Button @click="handleCancel">取消</Button>
        <Button type="primary" @click="handleAddOrUpdate">提交</Button>
      </Space>
    </template>
    <Form
      ref="formRef"
      :label-col="{ style: { width: '110px' } }"
      :model="form"
      :rules="rules"
      :wrapper-col="{ span: 20 }"
    >
      <FormItem label="应用" name="appId">
        <Select
          v-model:value="form.appId"
          :field-names="{ label: 'name', value: 'id' }"
          :options="appSelectList"
          placeholder="请选择应用"
        />
      </FormItem>
      <FormItem label="套餐类型" name="type">
        <Input v-model:value="form.type" placeholder="请输入套餐类型" />
      </FormItem>
      <FormItem label="企业规模" name="enterpriseSize">
        <Input v-model:value="form.enterpriseSize" placeholder="请输入企业规模" />
      </FormItem>
      <FormItem label="是否支持扩容" name="isExpand">
        <Switch v-model:checked="form.isExpand" />
      </FormItem>
      <FormItem label="License" name="ifWithLicense">
        <Switch v-model:checked="form.ifWithLicense" />
      </FormItem>
      <FormItem :hidden="!form.isExpand" label="套餐规格" name="appspecificationId">
        <Input v-model:value="form.specification" placeholder="请输入套餐规格" />
      </FormItem>
      <FormItem label="数据库多租类型" name="dbMultiTenantMode">
        <Select
          ref="select"
          v-model:value="form.dbMultiTenantMode"
          :options="dbMultiTenantMode"
          placeholder="请选择数据库多组类型"
        />
      </FormItem>
      <FormItem label="应用多租类型" name="appMultiTenantMode">
        <Select
          ref="select"
          v-model:value="form.appMultiTenantMode"
          :options="appMultiTenantMode"
          placeholder="请选择应用多组类型"
        />
      </FormItem>
      <FormItem label="云市场skuCode" name="skuCode">
        <Input v-model:value="form.skuCode" placeholder="请输入云市场skuCode" />
      </FormItem>
      <FormItem label="云市场ProductId">
        <Input v-model:value="form.productIds[0]" placeholder="请输入云市场ProductId" />
      </FormItem>
      <Space
        v-for="(sight, index) in form.itemIds"
        :key="sight.id"
        align="baseline"
        style="display: flex; margin-bottom: 8px"
      >
        <FormItem label="云市场ProductId">
          <Input
            v-model:value="form.itemIds[index].productId"
            placeholder="请输入云市场ProductId"
            style="width: 180%"
          />
        </FormItem>
        <MinusCircleOutlined style="margin-left: 1100%" @click="remove(sight)" />
      </Space>
      <FormItem>
        <Button block style="width: 120%; margin-right: 8px" type="dashed" @click="add">
          <PlusOutlined />
          添加云市场ProductId
        </Button>
      </FormItem>
    </Form>
  </Modal>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { Button, Form, FormItem, Input, Modal, Select, Space, Switch } from 'ant-design-vue';
import { SelectData } from '../data';
import { addOrUpdateInstance, getInstanceTypes } from '/@/api/system-mgmt/instance-mgmt/instance';
import { InstanceSaveDto } from '/@/api/system-mgmt/instance-mgmt/model/instanceModel';
import { useMessage } from '/@/hooks/web/useMessage';
import { getTenantSideApps } from '/@/api/deployment-center/deployTask';
import { AppTemplateResp } from '/@/api/operation-center/common/model/commonModel';
import { Rule } from 'ant-design-vue/es/form';
import isNumeric from 'ant-design-vue/lib/_util/isNumeric';

const { createMessage } = useMessage();
const visible = ref(false);
const type = ref();
const formRef = ref();
const emits = defineEmits(['refresh']);
// 表单数据
let form = reactive<InstanceSaveDto>({
  id: '',
  appId: '',
  type: '',
  enterpriseSize: '',
  isExpand: false,
  specification: '',
  itemIds: [],
  ifWithLicense: false,
  skuCode: '',
  productIds: [],
  dbMultiTenantMode: '',
  appMultiTenantMode: '',
});
// 应用多租选择器数据
let appMultiTenantMode = ref<SelectData[]>([
  { label: 'SHARED', value: 'SHARED' },
  { label: 'NAMESPACE', value: 'NAMESPACE' },
]);

// 数据多租选择器
let dbMultiTenantMode = ref<SelectData[]>([
  { label: 'COLUMN', value: 'COLUMN' },
  { label: 'SCHEMA', value: 'SCHEMA' },
  { label: 'DATASOURCE', value: 'DATASOURCE' },
]);
// 校验
const rules: Record<string, Rule[]> = {
  appId: [{ required: true, message: 'Please select appId' }],
  type: [{ required: true, message: 'Please enter type' }],
  enterpriseSize: [{ required: true, message: 'Please enter enterpriseSize' }],
  isExpand: [{ required: true, message: 'Please select isExpand' }],
  ifWithLicense: [{ required: true, message: 'Please select ifWithLicense' }],
  specification: [{ required: true, message: 'Please enter specification' }],
  dbMultiTenantMode: [{ required: true, message: 'Please enter dbMultiTenantMode' }],
  appMultiTenantMode: [{ required: true, message: 'Please enter appMultiTenantMode' }],
};

// 动态增减表单
function add() {
  form.itemIds.push({
    productId: '',
  });
}

function remove(item: string) {
  let index = form.itemIds.indexOf(item);
  if (index !== -1) {
    form.itemIds.splice(index, 1);
  }
}

const handleCancel = function () {
  visible.value = false;
  formRef.value.resetFields();
  emits('refresh');
};

// 应用下拉选择器的function
let appSelectList = ref<AppTemplateResp[]>([]);

async function handleAppChange() {
  await getTenantSideApps().then((res) => {
    appSelectList.value = res;
  });
}

// 保存新增和修改的数据
async function handleAddOrUpdate() {
  formRef.value.validate().then(async () => {
    if (type.value === 2 && !isNumeric(form.appId)) {
      form.appId = appSelectList.value.find((re) => re.name === form.appId).id;
    }
    await addOrUpdateInstance(form)
      .then(() => {
        if (type.value === 1) {
          createMessage.success('套餐创建成功！');
        } else {
          createMessage.success('套餐编辑成功！');
        }
      })
      .catch((e) => {
        if (type.value === 1) {
          createMessage.error('套餐创建失败！' + e.response.message);
        } else {
          createMessage.error('套餐编辑失败！' + e.response.message);
        }
      });
    handleCancel();
  });
}

function openModal(typeParam: number, record: Recordable) {
  visible.value = true;
  type.value = typeParam;
  if (typeParam === 2) {
    getInstanceTypes(record.appId).then((res) => {
      let newRes = res.find((it) => record.id === it.id);
      form.appId = String(appSelectList.value.find((re) => re.id === newRes.appId).name);
      form.appMultiTenantMode = newRes.appMultiTenantMode;
      form.dbMultiTenantMode = newRes.dbMultiTenantMode;
      form.enterpriseSize = newRes.enterpriseSize;
      form.ifWithLicense = newRes.ifWithLicense;
      form.isExpand = newRes.isExpand;
      form.skuCode = newRes.skuCode;
      form.specification = newRes.specification;
      form.type = newRes.type;
      form.id = newRes.id;
    });
  }
}

handleAppChange();
defineExpose({ openModal });
</script>
